/* eslint  react/no-string-refs: 0 */
import React, { Component } from 'react';
import IceContainer from '@icedesign/container';
import { Input, Grid, Form, Select, Radio, Field } from '@alifd/next';
import { observer, inject } from 'mobx-react';
import './EditForm.scss';
import { ApiOfPolicyCreate, ApiOfPolicyUpdate } from '#/utils/policyApiDefine'
import { ApiOfMetricGroupList, ApiOfMetricList } from '#/utils/coreApiDefine'
import { json } from 'graphlib';
const { Row, Col } = Grid;
const FormItem = Form.Item;
const RadioGroup = Radio.Group;

const formItemLayout = {
  labelCol: { xxs: 6, s: 3, l: 4 },
  wrapperCol: { s: 12, l: 12 }
};

@inject('dictstore')
@observer
export default class SettingsForm extends Component {
  static displayName = 'EditForm';
  static propTypes = {};
  static defaultProps = {};
  field = new Field(this);    // 实例创建

  constructor(props) {
    super(props);
    let formData = { ...this.props.formData };
    this.renderFrequency(formData);
    this.state = {
      value: {
        id: formData.id,
        code: formData.code,
        name: formData.name,
        description: formData.description,
        frequency: formData.frequency,
        criterion: {},
        time: formData.time,
        times: formData.times,
        metricCode: formData.metricCode ? formData.metricCode : '',
        type: formData.type ? formData.type : '',
        sign: formData.sign ? formData.sign : '',
        threshold: formData.threshold ? formData.threshold : '',
        policyType: formData.policyType,
        contentTemplate: formData.contentTemplate,
        expressions: formData.expressions
      },
      availableMetricDS: []
    };
    // this.handleMetricGroupChange = this.handleMetricGroupChange.bind(this);
  }
  componentWillMount() {
    // ApiOfMetricGroupList().then(response => {
    //   const { data } = response;
    //   var metrics = new Array();
    //   data.map(function (item, key, ary) {
    //     let metricKPS = item.metrics.map(function (i, key, ary) {
    //       return { value: i.code, label: item.name + ':' + i.name };
    //     });
    //     metrics.push.apply(metrics, metricKPS);
    //   });
    //   this.setState({
    //     availableMetricDS: metrics,
    //   });
    // })
    ApiOfMetricList().then(response => {
      const { data } = response;
      let metrics = data.map(function (item, key, ary) {
        return { value: item.code, label: item.name };
      });
      this.setState({
        availableMetricDS: metrics,
      });
    })
  }
  // handleMetricGroupChange(value) {
  //   const metricGroup = this.state.metricGroupDS;
  //   for (let data of metricGroup) {
  //     if (data.value == value) {
  //       let metricKPs = data.label.map(function (item, key, ary) {
  //         return { value: item.code, label: item.metrics };
  //       });
  //       this.setState({
  //         availableMetricDS: metricKPs,
  //       });
  //     }
  //   };
  // }
  formChange = (value) => {
    this.setState({
      value,
    });
  };

  validateAllFormField = (values, errors) => {
    let that = this;
    if (!errors) {
      let updated = values.id !== undefined;
      if (values.frequency == 'true') {
        let frequency = {};
        frequency.time = values.time;
        frequency.times = values.times;
        values.criterion['frequency'] = JSON.stringify(frequency);
        values.criterion = JSON.stringify(values.criterion);
      } else {
        values.criterion = null;
      }
      if (values.metricCode) {
        let expressionInfo = {};
        expressionInfo.metricCode = values.metricCode;
        expressionInfo.sign = values.sign;
        expressionInfo.threshold = values.threshold;
        let expression = {};
        expression.expressionInfo = JSON.stringify(expressionInfo);
        expression.type = values.type;
        if (values.expressions && values.expressions != undefined) {
          expression.id = values.expressions[0].id;
          values.expressions[0] = expression;
        } else {
          values.expressions = new Array;
          values.expressions.push(expression);
        }
        let contentTemplate = {};
        contentTemplate[0] = values.metricCode + '(当前值#' + values.metricCode + '#)' + values.sign + values.threshold;
        values.contentTemplate = JSON.stringify(contentTemplate);
      }
      if (updated) {
        ApiOfPolicyUpdate(values.code, values).then(() => that.props.submitCallback('success'))
      } else {
        ApiOfPolicyCreate(values).then(() => that.props.submitCallback('success'))
      }
    } else {
      // 处理表单报错
    }
  };
  // 渲染解析规则JSON显示
  renderFrequency = (formData) => {
    formData.frequency = 'false';
    if (formData.criterion && formData.criterion != undefined) {
      let criterion = JSON.parse(formData.criterion);
      if (criterion['frequency']) {
        let frequency = JSON.parse(criterion['frequency']);
        formData.time = frequency['time'];
        formData.times = frequency['times'];
        formData.frequency = 'true';
      }
    }
    if (formData.expressions && formData.expressions != undefined) {
      let expressions = formData.expressions;
      console.log(expressions);
      for (let data of expressions) {
        formData.type = data.type;
        let expressionInfo = JSON.parse(data.expressionInfo);
        formData.sign = expressionInfo['sign'];
        formData.threshold = expressionInfo['threshold'];
        formData.metricCode = expressionInfo['metricCode'];
      }
    }
  };
  render() {
    const init = this.field.init;
    return (
      <div className="settings-form">
        <IceContainer>
          <Form
            value={this.state.value}
            onChange={this.formChange}
            ref="form"
          >
            <div style={styles.formContent}>
              <Input name="id" htmlType="hidden" />
              <Input name="code" htmlType="hidden" />
              <Input name="expressions" htmlType="hidden" />
              <FormItem size="medium" label="名称：" {...formItemLayout} required maxLength={30} requiredMessage="必填">
                <Input name="name" placeholder="策略名称" />
              </FormItem>
              <FormItem size="medium" label="描述：" {...formItemLayout} required maxLength={200} requiredMessage="必填">
                <Input.TextArea name="description" placeholder="策略描述" />
              </FormItem>
              {/* <FormItem size="medium" label="指标组：" {...formItemLayout} >
                <Select name="mestricGroupCode" dataSource={this.state.availableMetricGroupDS} hasClear={true} onChange={this.handleMetricGroupChange} style={{ width: '100%' }} placeholder="请选择指标组" />
              </FormItem> */}
              <FormItem size="medium" label="指标：" {...formItemLayout}>
                <Select name="metricCode" dataSource={this.state.availableMetricDS} hasClear={true} style={{ width: '100%' }} placeholder="请选择指标" />
              </FormItem>
              <FormItem size="medium" label="条件：" {...formItemLayout} required requiredMessage="必填">
                <FormItem size="medium"><Select name="type" dataSource={this.props.dictstore.PolicyExpTypeDS} hasClear={true} style={{ width: '100%' }} /></FormItem>
                <FormItem size="medium"><Select name="sign" dataSource={this.props.dictstore.PolicyExpSignDS} hasClear={true} style={{ width: '100%' }} /></FormItem>
                <FormItem size="medium"><Input name="threshold" /></FormItem>
              </FormItem>
              <FormItem size="medium" label="执行频次：" {...formItemLayout} >
                {/* <Input.TextArea name="frequency" placeholder="{... ...}" /> */}
                <RadioGroup name="frequency">
                  <Radio value="false">满足条件时</Radio>
                  <Radio value="true">
                    <FormItem size="medium">在<Input name="time" placeholder="时间(毫秒)" />内触发<Input name="times" placeholder="次数" />次才执行
                    </FormItem></Radio>
                </RadioGroup>
              </FormItem>
              <FormItem size="medium" label="事件类型：" {...formItemLayout} required requiredMessage="必填">
                <Select name="policyType" dataSource={this.props.dictstore.PolicyTypeDS} hasClear={true} style={{ width: '100%' }} />
              </FormItem>
              {/* <FormItem size="medium" label="事件内容：" {...formItemLayout} >
                <Input.TextArea name="contentTemplate" placeholder="{... ...}" />
              </FormItem> */}
              <Row style={{ marginTop: 20 }}>
                <Col offset="3">
                  <Form.Submit
                    size="medium"
                    type="primary"
                    style={{ width: 100 }}
                    validate
                    onClick={this.validateAllFormField}
                  >
                    保 存
              </Form.Submit>
                </Col>
              </Row>
            </div>
          </Form>
        </IceContainer>
      </div >
    );
  }
}

const styles = {
  label: {
    textAlign: 'right',
  },
  formContent: {
    width: '100%',
    position: 'relative',
  },
  formItem: {
    alignItems: 'center',
    marginBottom: 25,
  },
  formTitle: {
    margin: '0 0 20px',
    paddingBottom: '10px',
    borderBottom: '1px solid #eee',
  },
};
